<?php

namespace fakis\core\helpers;

use yii\helpers\ArrayHelper;
use yii\helpers\Html;

/**
 * Class Avatar
 *
 * @author Fakis <fakis738@qq.com>
 */
class Avatar
{
    /**
     * 返回文字头像svg格式base64数据
     * @param string $text
     * @param array $options
     * @return string
     */
    public static function toBase64(string $text, array $options = []): string
    {
        $hue = unpack('L', hash('adler32', $text, true))[1] % 360;
        $h = ArrayHelper::getValue($options, 'h', $hue);
        $s = ArrayHelper::getValue($options, 's', 0.7);
        $v = ArrayHelper::getValue($options, 'v', 0.7);
        $size = ArrayHelper::getValue($options, 'size', 200);

        $rgb = implode(',', Color::hsv2rgb($h, $s, $v));
        $bg = "rgb({$rgb})";
        $color = '#ffffff';

        // 全是汉字，取前1位；不全是汉字，取前2位
        $text = mb_substr(trim($text), 0, 2);
        if (preg_match('/^\w+$/', $text)) {
            $char = $text;
            $fontSize = ceil($size / 2.4);
        } else {
            $char = mb_substr($text, 0, 1);
            $fontSize = ceil($size / 2);
        }
//        $char = preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $text) ? mb_substr($text, -2) : mb_substr($text, 0, 2);

        $position = ceil($size / 2);

        $svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="' . $size . '" width="' . $size . '"><rect fill="' . $bg . '" x="0" y="0" width="' . $size . '" height="' . $size . '"></rect><text x="' . $position . '" y="' . $position . '" font-size="' . $fontSize . '" fill="' . $color . '" text-anchor="middle" alignment-baseline="central">' . $char . '</text></svg>';
        return 'data:image/svg+xml;base64,' . base64_encode($svg);
    }

    /**
     * 返回文字头像图片标签
     * 调用 [[toBase64()]]
     * @param string $text
     * @param array $options
     * @param array $imgOptions
     * @return string
     */
    public static function toImage(string $text, array $options = [], array $imgOptions = []): string
    {
        return Html::img(static::toBase64($text, $options), $imgOptions);
    }
}
